//
//  AppDelegate.m
//  天气预报
//
//  Created by wangda on 15/7/10.
//  Copyright (c) 2015年 wang. All rights reserved.
//

#import "AppDelegate.h"
//#import "ViewController.h"
#import "mainViewController.h"
#import "cityListViewController.h"
#import "addCityViewController.h"

#import <sqlite3.h>

@interface AppDelegate ()
@end

@implementation AppDelegate
-(NSMutableArray *)citys
{
    if (_citys == nil) {
        
     
        NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString * docDirectory = paths[0];
        NSString *dateBaseSt = [docDirectory stringByAppendingPathComponent:@"date.sqlite"];
        sqlite3 * database;
        //NSLog(@"ready to open,path is %@",dateBaseSt);
        //打开数据库
        if (sqlite3_open([dateBaseSt UTF8String], &database) != SQLITE_OK ) {
            sqlite3_close(database);
            //中断程序
            NSAssert(0, @"failed to open database");
        }
        
        NSString *sqlQuery = @"SELECT * FROM CITYS ";
        sqlite3_stmt * statement;
        
        _citys = [[NSMutableArray alloc]init];
        
        if (sqlite3_prepare_v2(database, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                char *cityname = (char*)sqlite3_column_text(statement, 1);
                NSString *nsNameStr = [[NSString alloc]initWithUTF8String:cityname];
                int id = sqlite3_column_int(statement, 0);
                [_citys insertObject:nsNameStr atIndex:id];
                //NSLog(@"addddd is ok");
            }
        }
        
        //[self closeDB];
        sqlite3_close(database); //记得关闭，打开就要记得关闭
        
    }
    
    return _citys;
}


-(void)existDateBase
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * docDirectory = paths[0];
    NSString *dateBaseSt = [docDirectory stringByAppendingPathComponent:@"date.sqlite"];
    //NSLog(@"数据库的地址为%@",docDirectory);
    sqlite3 * database;
    
    //打开数据库
    if (sqlite3_open([dateBaseSt UTF8String], &database) != SQLITE_OK ) {
        sqlite3_close(database);
        //中断程序
        NSAssert(0, @"failed to open database");
    }
   
     //创建表,行号和文本框内容
     NSString * createSQL = @"CREATE TABLE IF NOT EXISTS CITYS (ID INTEGER PRIMARY KEY AUTOINCREMENT ,CITY_NAME TEXT)";
     char * errorMsg;
     if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {
     sqlite3_close(database);
     //中断程序
     NSAssert(0, @"创建城市表失败 %s",errorMsg);
     }
   // NSString *TABLENAME = @"CITYS";
    //添加数据的代码
    // NSString *sql2 = [NSString stringWithFormat:@"INSERT INTO '%@' ('%@', '%@') VALUES ('%d', '%@')",                     TABLENAME, @"ID", @"CITY_NAME", 4, @"深圳"];
    
    //[self execSql:sql2 and:database];
   /*查询的相关代码
    NSString *sqlQuery = @"SELECT * FROM CITYS";
    sqlite3_stmt * statement;
    
    if (sqlite3_prepare_v2(database, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            char *cityname = (char*)sqlite3_column_text(statement, 1);
           // NSString *nsNameStr = [[NSString alloc]initWithUTF8String:cityname];
            NSString *nsNameStr = [[NSString alloc]initWithUTF8String:cityname];
            
            int id = sqlite3_column_int(statement, 0);
            //NSLog(@"name:%@  id:%d  ",nsNameStr,id);
        }
    }*/
     sqlite3_close(database);
    // NSLog(@"数据库关闭");
    
}

-(void)execSql:(NSString *)sql  and:(sqlite3 *)db
{
    char *err;
    if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        sqlite3_close(db);
        NSLog(@"数据库操作数据失败!");
       // NSLog(@"%s--------",err);
    }
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    //mainViewController *nav = [[mainViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]init];
    
    [nav setNavigationBarHidden:YES];
    mainViewController *m1 = [[mainViewController alloc]init];
    

    cityListViewController *cityList = [[cityListViewController alloc]initWithNibName:@"cityListViewController" bundle:nil];
    //city.view.backgroundColor = [UIColor redColor];
    
    addCityViewController *addCity = [[addCityViewController alloc]initWithNibName:@"addCityViewController" bundle:nil];
    //addCityViewController *addCity = [[addCityViewController alloc]init];
    //addCity.view.backgroundColor = [UIColor whiteColor];
    
    nav.viewControllers = @[cityList,addCity,m1];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    
    [self existDateBase];
   // NSLog(@"in  appdeletegae");
    return YES;
 
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
  //   [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * docDirectory = paths[0];
    
    NSString *dateBaseSt = [docDirectory stringByAppendingPathComponent:@"date.sqlite"];
   
    FMDatabase *db = [FMDatabase databaseWithPath:dateBaseSt];
    if (![db open]) {
        NSLog(@"cannt open");
    }
    [db executeUpdate:@"drop table if exists CITYS;"];
    [db executeUpdate:@"create table  CITYS (ID integer  ,NAME text );"];

    NSLog(@"-----path is %@",dateBaseSt);
    NSLog(@"-----COU IS %d",self.citys.count);
    for (int i = 0; i<self.citys.count; i++) {
        [db executeUpdate:@"INSERT INTO CITYS (ID, NAME) VALUES (?, ?);",
         [NSNumber numberWithInt:i],self.citys[i]];
    }
    [db close];
    /*
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * docDirectory = paths[0];
    NSString *dateBaseSt = [docDirectory stringByAppendingPathComponent:@"date.sqlite"];
    //NSLog(@"数据库的地址为%@",docDirectory);
    sqlite3 * database;
    
    //打开数据库
    if (sqlite3_open([dateBaseSt UTF8String], &database) != SQLITE_OK ) {
        sqlite3_close(database);
        //中断程序
        NSAssert(0, @"failed to open database");
    }
    
   
    
    sqlite3_stmt *statement;
    //组织SQL语句
    static char *sql = "delete *from CITYS";
    //将SQL语句放入sqlite3_stmt中
    int success = sqlite3_prepare_v2(database, sql, -1, &statement, NULL);
    if (success != SQLITE_OK) {
        NSLog(@"Error: failed to delete:testTable");
        sqlite3_close(database);
    }
   
    for (int i = 0; i <self.citys.count; i++) {
        //添加数据的代码
         char *sql = "insert or replace into CITYS (ID,CITY_NAME)values(?,?); ";
        char *errorMsg = NULL;
        sqlite3_stmt *statement1;
        if ((sqlite3_prepare_v2(database, sql , -1, &statement1, nil))==SQLITE_OK) {
            sqlite3_bind_int(statement1, 1, i);
            sqlite3_bind_text(statement1, 2, [self.citys[i]UTF8String ], -1, NULL);
        }
        
        if (sqlite3_step(statement1)!=SQLITE_DONE) {
            NSAssert(0, @"更新出错%s",errorMsg);
        }
        sqlite3_finalize(statement1);
    }
    sqlite3_close(database);
   

    */
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
       [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
